founderHistoryTable = null;
securityIdentities = null;

(function($)
{
	$(document).ready(function()
	{
		listSecurityIdentities();
		
		founderTable = $('#founderTable').dataTable(
		{
			bRetrieve : true,
			bProcessing : false,
			bServerSide : true,
			bFilter : false,
			bInfo : true,
			bLengthChange : false,
			bSort : true,
			sAjaxDataProp: 'founders',
			sServerMethod: 'POST',
			sPaginationType: 'full_numbers',
			sAjaxSource : '{0}/founder/list'.format(contextPath),
			fnServerParams : function(aoData)
			{
				aoData.push(
				{
					name : "founderName",
					value : $('input[name="searchFounderName"]').val(),
				},
				{
					name : "cellNumber",
					value : $('input[name="searchCellNumber"]').val(),
				},
				{
					name : "region",
					value : $('select[name="searchRegion"]').val(),
				},
				{
					name : "age",
					value : $('select[name="searchAge"]').val(),
				},
				{
					name : "gender",
					value : $('select[name="searchGender"]').val(),
				},
				{
					name : "inflowRoute",
					value : $('select[name="searchInflowRoute"]').val(),
				},
				{
					name : "inChargeId",
					value : $('select[name="searchInChargeId"]').val(),
				});
			},
			aoColumns :
			[
				{
					sTitle : '고객명',
					mDataProp : 'founderName',
					bSortable : true,
					asSorting : [ 'asc', 'desc' ],
					sClass : 'center'
				},
				{
					sTitle : '휴대 전화',
					mDataProp : 'cellNumber',
					bSortable : true,
					asSorting : [ 'asc', 'desc' ],
					sClass : 'nosort',
					sDefaultContent: '-'
				},
				{
					sTitle : '지역',
					mDataProp : 'region',
					bSortable : true,
					sDefaultContent: '-'
				},
				{
					sTitle : '나이',
					mDataProp : 'age',
					bSortable : true,
					sDefaultContent: '-'
				},
				{
					sTitle : '성별',
					mDataProp : 'gender',
					bSortable : true,
					sDefaultContent: '-'
				},
				{
					sTitle : '직업',
					mDataProp : 'occupation',
					bSortable : true,
					sDefaultContent: '-'
				},
				{
					sTitle : '유입 경로',
					mDataProp : 'inflowRoute',
					bSortable : true,
					sDefaultContent: '-'
				}
			],
			fnInfoCallback : function(oSettings, iStart, iEnd, iMax, iTotal, sPre)
			{
				return "전체 " + iMax + "건 중 " + iStart + "부터 " + (iMax < iEnd ? iMax : iEnd) + "까지";
			}
		});
		
		$('#founderTable tbody').unbind('click').delegate('tr', 'click', function(event)
		{
			var founder = founderTable.fnGetData(this);
			
			$('input[name="selectedId"]').val(founder.founderId);
			
			showFounderEditPopup(event);
		});
		
		$('form[name="searchForm"] select').change(function(event) { founderTable.fnDraw(); });
		
		$('#searchButton').unbind('click').click(function(event){ founderTable.fnDraw(); });
		
		$('#registerButton').unbind('click').click(showFounderEditPopup);
		$('#resetButton').unbind('click').click(resetEditForm);
	});
	
	/**
	 * 창업주 편집 팝업을 개방한다.
	 */
	function showFounderEditPopup(event)
	{
		var popupContents = '<div class="maincontent">' +
				'<div class="contentinner content-editprofile">' +
				'<h4 class="widgettitle nomargin">창업주 편집</h4>' +
				'<div class="widgetcontent bordered" style="overflow: auto; height: 740px;">' +
					'<form id="founderEditForm" action="{0}/founder/save" class="editprofileform" method="post">' +
					'<input type="hidden" name="founderId" />' +
						'<div class="row-fluid">' +
							'<div class="span8">' +
								'<p>' +
									'<label>고객명</label>' +
									'<span class="field"><input type="text" name="founderName" class="input-medium" /></span>' +
								'</p>' +
							'</div>' +
							'<div class="span4">' +
								'<p>' +
									'<label>담당자</label>' +
									'<span class="field">' +
										'<select name="inChargeId" class="uniformselect span5">' +
											'<option value="">선택</option>' +
										'</select>' +
									'</span>' +
								'</p>' +
							'</div>' +
						'</div>' +
						'<div class="row-fluid">' +
							'<div>' +
								'<p>' +
									'<label>창업 목적/특징</label>' +
									'<span class="field"><input type="text" name="purposeFeature" class="input-xxlarge" placeholder="" /></span>' +
								'</p>' +
							'</div>' +
						'</div>' +
						'<div class="row-fluid">' +
							'<div class="span4">' +
								'<h4>고객 내역</h4>' +
								'<p>' +
									'<label>접수일</label>' +
									'<input type="text" name="receiptionTimestamp" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>휴대폰 번호</label>' +
									'<input type="text" name="cellNumber" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>연락처</label>' +
									'<input type="text" name="phoneNumber" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>지역</label>' +
									'<select name="region" class="uniformselect span5">' +
										'<option value="">선택</option>' +
										'<option value="1">서울</option>' +
										'<option value="2">경기</option>' +
										'<option value="3">인천</option>' +
										'<option value="4">부산</option>' +
										'<option value="5">광주</option>' +
										'<option value="6">대구</option>' +
										'<option value="7">울산</option>' +
										'<option value="8">충청</option>' +
										'<option value="9">경상</option>' +
										'<option value="10">전라</option>' +
										'<option value="11">제주</option>' +
									'</select>' +
								'</p>' +
								'<p>' +
									'<label>나이</label>' +
									'<input type="text" name="age" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>성별</label>' +
									'<select name="gender" class="uniformselect span5">' +
										'<option value="">선택</option>' +
										'<option value="1">남성</option>' +
										'<option value="2">여성</option>' +
									'</select>' +
								'</p>' +
								'<p>' +
									'<label>직업</label>' +
									'<input type="text" name="occupation" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>결정권자</label>' +
									'<input type="text" name="decisionMaker" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>구입 상세내역</label>' +
									'<textarea name="orderDetails" class="span7"></textarea>' +
								'</p>' +
							'</div>' +
							'<div class="span4">' +
								'<h4>창업 조건</h4>' +
								'<p>' +
									'<label>유입 경로</label>' +
									'<select name="inflowRoute" class="uniformselect span5">' +
										'<option value="">선택</option>' +
										'<option value="1">홈페이지</option>' +
										'<option value="2">카페</option>' +
										'<option value="3">블로그</option>' +
										'<option value="4">기타</option>' +
									'</select>' +
								'</p>' +
								'<p>' +
									'<label>창업 자금</label>' +
									'<input type="text" name="grossCapital" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>희망 수익</label>' +
									'<input type="text" name="expectedEarning" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>선호 지역</label>' +
									'<input type="text" name="regionPreference" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>운영 방식</label>' +
									'<input type="text" name="operationMethod" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>창업 경험</label>' +
									'<input type="text" name="foundingExperience" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>창업 시기</label>' +
									'<input type="text" name="foundingTime" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>유입 키워드</label>' +
									'<textarea name="inflowKeyword" class="span7"></textarea>' +
								'</p>' +
							'</div>' +
							'<div class="span4">' +
								'<h4>추진 내역</h4>' +
								'<p>' +
									'<label>고객 상태</label>' +
									'<input type="text" name="founderStatus" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>추진 물건A</label>' +
									'<input type="text" name="ongoingFoundation1" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>추진 물건B</label>' +
									'<input type="text" name="ongoingFoundation2" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>추진 물건C</label>' +
									'<input type="text" name="ongoingFoundation3" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>미팅 내역A</label>' +
									'<input type="text" name="meetingHistory1" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>미팅 내역B</label>' +
									'<input type="text" name="meetingHistory2" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>미팅 내역C</label>' +
									'<input type="text" name="meetingHistory3" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>기타</label>' +
									'<textarea name="referenceDetails" class="span7"></textarea>' +
								'</p>' +
							'</div>' +
						'</div>' +
					'</form>' +
					'<form id="founderHistoryForm" action="" class="editprofileform" method="post">' +
					'<input type="hidden" name="founderId" />' +
						'<div id="founderHistoryDom" class="row-fluid" style="display: none;">' +
							'<div>' +
								'<h4>작업 내역</h4>' +
								'<div style="overflow: auto; height: 220px;">' +
									'<table id="founderHistoryTable" class="table table-bordered"></table>' +
								'</div>' +
								'<div class="divider10"></div>' +
								'<div>' +
									'<input type="text" name="contents" class="input-xlarge" value="" /> <a href="#" id="historyAddButton" class="btn btn-info">입력</a>' +
								'</div>' +
							'</div>' +
						'</div>' +
					'</form>'+
					'<div class="divider15"></div>' +
					'<div>' +
						'<button id="resetButton" type="button" class="btn">새 창업주</button> ' +
						'<button id="saveButton" type="submit" class="btn btn-primary">저장</button> ' +
						'<button id="printButton" type="button" class="btn">인쇄</button> ' +
					'</div>' +
				'</div><!--widgetcontent-->' +
			'</div><!--contentinner-->' +
		'</div><!--maincontent-->';
		
		popupContents = popupContents.format(contextPath);
		
		$(this).speedoPopup(
		{
			theme : 'default',
			width : 1040,
			height : 820,
			onShow : editPopupShown,
			onComplete : editPopupComplete,
			onClose : editPopupClosed,
			htmlContent : popupContents
		});
	}
	
	/**
	 * 편집 팝업의 구성이 완료된 뒤에 실행된다.(최초에 한번만 실행된다.)
	 */
	function editPopupComplete(event)
	{
		securityIdentitiesToSelect('inChargeId');
	}
	
	/**
	 * 창업주 편집 팝업이 개방된 뒤에 실행된다.
	 */
	function editPopupShown(event)
	{
		$('#saveButton').unbind('click').click(saveFounder);
		
		var founderId = $('input[name="selectedId"]').val();
		
		// 창업주를 새로 등록하는 경우 이후 과정은 수행하지 않는다.
		if (!founderId || founderId < 1)
		{
			return;
		}
		
		getFounder(founderId);
		
		// 창업주 작업 내역 DOM을 보여준다.
		$('#founderHistoryDom').css('display', $(this).founder ? 'none' : 'block');
	}
	
	function editPopupClosed(event)
	{
		resetEditForm();
		resetHistoryForm();
	}
	
	/**
	 * 창업주 편집 폼을 초기 상태로 되돌린다. 
	 */
	function resetEditForm(event)
	{
		$("#founderEditForm").each(function()
		{
			this.reset();
		});
	}
	
	/**
	 * 창업주 작업 내역 폼을 초기 상태로 되돌린다.
	 */
	function resetHistoryForm(event)
	{
		$("#founderHistoryForm").each(function()
		{
			this.reset();
		});
	}
	
	/**
	 * 창업주 정보를 편집 폼에 설정한다.
	 */
	function setFounderToForm(founder)
	{
		$('input[name="founderId"]').val(founder.founderId);
		$('input[name="founderName"]').val(founder.founderName);
		$('select[name="inChargeId"]').val(founder.inChargeId);
		$('input[name="purposeFeature"]').val(founder.purposeFeature);
		$('input[name="receiptionTimestamp"]').val(founder.receiptionTimestamp);
		$('input[name="cellNumber"]').val(founder.cellNumber);
		$('input[name="phoneNumber"]').val(founder.phoneNumber);
		$('input[name="region"]').val(founder.region);
		$('input[name="age"]').val(founder.age);
		$('input[name="gender"]').val(founder.gender);
		$('input[name="occupation"]').val(founder.occupation);
		$('input[name="decisionMaker"]').val(founder.decisionMaker);
		$('input[name="orderDetails"]').val(founder.orderDetails);
		$('input[name="inflowRoute"]').val(founder.inflowRoute);
		$('input[name="categoryPreference"]').val(founder.categoryPreference);
		$('input[name="grossCapital"]').val(founder.grossCapital);
		$('input[name="expectedEarning"]').val(founder.expectedEarning);
		$('input[name="regionPreference"]').val(founder.regionPreference);
		$('input[name="operationMethod"]').val(founder.operationMethod);
		$('input[name="foundingExperience"]').val(founder.foundingExperience);
		$('input[name="foundingTime"]').val(founder.foundingTime);
		$('input[name="inflowKeyword"]').val(founder.inflowKeyword);
		$('input[name="founderStatus"]').val(founder.founderStatus);
		$('input[name="ongoingFoundation1"]').val(founder.ongoingFoundation1);
		$('input[name="ongoingFoundation2"]').val(founder.ongoingFoundation2);
		$('input[name="ongoingFoundation3"]').val(founder.ongoingFoundation3);
		$('input[name="meetingHistory1"]').val(founder.meetingHistory1);
		$('input[name="meetingHistory2"]').val(founder.meetingHistory2);
		$('input[name="meetingHistory3"]').val(founder.meetingHistory3);
		$('input[name="referenceDetails"]').val(founder.referenceDetails);
	}
	
	/**
	 * 창업주 편집 폼의 유효성 점검을 설정한다.
	 */
	function installFounderEditFormValidation()
	{
		$("#founderEditForm").validate(
		{
			rules :
			{
				founderName : "required",
				inChargeId : "required"
			},
			messages :
			{
				founderName : "고객명을 입력해 주시기 바랍니다.",
				inChargeId : "담당자를 지정해 주시기 바랍니다."
			},
			highlight : function(label)
			{
				$(label).closest('.control-group').addClass('error');
			},
			success : function(label)
			{
				var message = "";
				
				switch(label.attr('for'))
				{
					case 'founderName' :
						
						message = "고객명이 정상적으로 입력되었습니다.";
						
						break;
						
					case 'inChargeId' :
						
						message = "담당자가 정상적으로 선택되었습니다.";
						
						break;
				}
				
				label.text(message).addClass('valid').closest('.control-group').addClass('success');
			}
		});
	}
	
	/**
	 * 보안 계정 목록을 요청한다.
	 */
	function listSecurityIdentities()
	{
		$.ajax(
		{
			url : '{0}/security/identity/list'.format(contextPath),
			type : 'post',
			cache : false,
			dataType : 'json',
			success : listSecurityIdentitiesCallback
		});
	}
	
	/**
	 * 보안 계정 목록 요청에 대한 콜백이 실행된다.
	 */
	function listSecurityIdentitiesCallback(data)
	{
		securityIdentities = data.identities;
		
		securityIdentitiesToSelect('searchInChargeId');
	}
	
	/**
	 * 담당자 Select에 담당자 목록을 나열한다.
	 */
	function securityIdentitiesToSelect(controlName)
	{
		$('select[name="' + controlName + '"] option').remove();
		
		$('select[name="' + controlName + '"]').append('<option value="">선택</option>');
		
		for (var index in securityIdentities)
		{
			var identity = securityIdentities[index];
			
			$('select[name="' + controlName + '"]').append('<option value="{0}">{1}</option>'.format(identity.identityId, identity.name));
		}
	}
	
	/**
	 * 주어진 창업주 아이디에 대한 창업주 정보를 요청한다.
	 */
	function getFounder(founderId)
	{
		$.ajax(
		{
			url : '{0}/founder/get'.format(contextPath),
			type : 'post',
			cache : false,
			data : { founderId : founderId },
			dataType : 'json',
			success : getFounderCallback
		});
	}
	
	/**
	 * 창업주 정보 요청에 대한 콜백이 실행된다.
	 */
	function getFounderCallback(data)
	{
		setFounderToForm(data.founder);
		
		$('#founderHistoryDom').css('display', 'block');
		
		if (!founderHistoryTable)
		{
			installFounderHistoryTable();
		}
		else
		{
			$('#founderHistoryTable').dataTable().fnDraw();
		}
		
		$('#historyAddButton').click(saveFounderHistory);
	}
	
	/**
	 * 창업주 저장을 요청한다.
	 */
	function saveFounder(event)
	{
		$(this).unbind('click');
		$(this).attr('disabled', true);
		
		
		$.ajax(
		{
			url : '{0}/founder/save'.format(contextPath),
			type : 'post',
			cache : false,
			data : $('#founderEditForm').serialize(),
			dataType : 'json',
			success : saveFounderCallback
		});
	}
	
	/**
	 * 창업주 저장 요청에 대한 콜백이 실행된다.
	 */
	function saveFounderCallback(data)
	{
		if (data.result)
		{
			if (founderHistoryTable)
			{
				$('#founderHistoryTable').dataTable();
			}
			else
			{
				installFounderHistoryTable();
			}
			
			$('#founderHistoryDom').css('display', 'block');
		}
		
		$('#saveButton').unbind('click').click(saveFounder);
		$('#saveButton').attr('disabled', false);
	}
	
	/**
	 * 창업주 작업 내역 테이블을 설정한다.
	 */
	function installFounderHistoryTable()
	{
		var founderId = $('input[name="founderId"]').val();
		
		founderHistoryTable = $('#founderHistoryTable').dataTable(
		{
			bRetrieve : true,
			bProcessing : false,
			bServerSide : true,
			bFilter : false,
			bInfo : false,
			bLengthChange : false,
			bSort : true,
			bPaginate : false,
			sAjaxDataProp: 'histories',
			sServerMethod: 'POST',
			sPaginationType: 'full_numbers',
			sAjaxSource : '{0}/founder/history/list'.format(contextPath),
			fnServerParams : function(aoData)
			{
				aoData.push( { name : "founderId", value : founderId } );
			},
			aoColumns :
			[
					{
						sTitle : '삭제',
						mDataProp : null,
						bSortable : false,
						sClass : 'center',
						sDefaultContent: '-',
						sWidth : '8%',
					},
					{
						sTitle : '일시',
						mDataProp : 'generatedTimestamp',
						sType : 'date',
						bSortable : true,
						asSorting : [ 'asc', 'desc' ],
						sClass : 'center',
						sDefaultContent: '-',
						sWidth : '15%',
						mRender : function(data, type, full)
						{
							return $.dateFormat.date(new Date(data), "yyyy-MM-dd HH:mm:ss");
						}
					},
					{
						sTitle : '내용',
						mDataProp : 'contents',
						bSortable : true,
						sDefaultContent: '-',
					}
			],
			fnInfoCallback : function(oSettings, iStart, iEnd, iMax, iTotal, sPre)
			{
				return "전체 " + iMax + "건 중 " + iStart + "부터 " + (iMax < iEnd ? iMax : iEnd) + "까지";
			}
		});
	}
	
	/**
	 * 창업주 작업 내역 저장을 요청한다.
	 */
	function saveFounderHistory(event)
	{
		if (!$('input[name="contents"]').val())
		{
			return;
		}
		
		$(this).attr('disabled', true);
		$(this).unbind('click');
		
		$.ajax(
		{
			url : '{0}/founder/history/save'.format(contextPath),
			type : 'post',
			cache : false,
			data : $('#founderHistoryForm').serialize(),
			dataType : 'json',
			success : saveFounderHistoryCallback
		});
	}
	
	/**
	 * 창업주 작업 내역 저장 요청에 대한 콜백이 실행된다.
	 */
	function saveFounderHistoryCallback(data)
	{
		resetHistoryForm();
		
		$('#historyAddButton').attr('disabled', false);
		$('#historyAddButton').click(saveFounderHistory);
		
		$('#founderHistoryTable').dataTable().fnDraw();
	}
}(jQuery));